import type { MyFavoritesProps, StylePropertyItem } from '../interfaces'
import { UIComponent } from '../../../lib/abstract'
import { logger } from '../../../types/constants'
import { SYMBOLS } from '../../../types/interfaces'
import { styles } from './styles'

export class MyFavorites extends UIComponent<MyFavoritesProps> {
  id: string = 'my-favorites'
  private favorites: StylePropertyItem[] = []
  private readonly storageKey = 'style_editor_favorites'
  private readonly emptyFavoritesText = '暂无设置常用样式，选择样式时点击收藏图标即可完成添加'
  private static instance: MyFavorites

  get className(): string {
    return 'my-favorites'
  }

  constructor(props?: MyFavoritesProps) {
    super(props)
    this.loadFavorites()
  }

  ELEMENT_SELECTORS = {
    favoritesContent: { selector: '.favorites-content', dynamic: false, unique: false },
    favoritesList: { selector: '.favorites-content .favorites-list', dynamic: true, unique: false },
    favoriteItem: { selector: '.favorites-content .favorite-item', dynamic: true, unique: false },
    noFavorites: { selector: '.favorites-content .no-favorites', dynamic: true, unique: false },
  }

  /**
   * 获取单例实例
   */
  static getInstance(props?: MyFavoritesProps): MyFavorites {
    if (!MyFavorites.instance) {
      MyFavorites.instance = new MyFavorites(props)
    }
    return MyFavorites.instance
  }

  render(): string {
    return `
      <div class="${this.className}">
        <div class="favorites-content">
            ${this.favorites.length === 0 ? this.renderNoFavorites() : this.renderItem()}
        </div>
      </div>
    `
  }

  /**
   * 渲染空状态
   */
  renderNoFavorites() {
    return `
      <div class="${this.className}">
        <div class="no-favorites">
          <div class="icon">${SYMBOLS.SHAPES.STAR_EMPTY}</div>
          <div class="text">${this.emptyFavoritesText}</div>
        </div>
      </div>
    `
  }

  /**
   * 渲染收藏项
   */
  renderItem() {
    return `
      <div class="favorites-list">
        ${this.favorites.map(item => `
          <div class="favorite-item" data-id="${item.id}">
            <span class="name">${item.label}</span>
            <span class="remove" title="移除收藏">${SYMBOLS.SHAPES.STAR_EMPTY}</span>
          </div>
        `).join('')}
      </div>
    `
  }

  /**
   * 从存储中加载收藏项
   */
  private loadFavorites() {
    const saved = this.storage.get(this.storageKey, '[]')
    try {
      this.favorites = JSON.parse(saved) || []
      logger.info(`[${this.name}] 已加载收藏项: ${this.favorites.length}个`)
    }
    catch (error: any) {
      logger.error(`[${this.name}] 加载收藏项失败:`, error)
      this.favorites = []
    }
  }

  /**
   * 保存收藏项到存储
   */
  private saveFavorites() {
    this.storage.set(this.storageKey, JSON.stringify(this.favorites))
    logger.info(`[${this.name}] 已保存最新收藏情况`)
  }

  /**
   * 添加收藏项
   * @param item 要添加的样式属性项
   */
  addFavorite(item: StylePropertyItem): void {
    if (!this.isFavorite(item.id)) {
      this.favorites.push(item)
      this.saveFavorites()
      logger.info(`[${this.name}] 已添加收藏: ${item.label}`)
      this.updateUI()
    }
  }

  /**
   * 移除收藏项
   * @param id 要移除的样式属性ID
   */
  removeFavorite(id: string): void {
    this.favorites = this.favorites.filter(fav => fav.id !== id)
    this.saveFavorites()
    logger.info(`[${this.name}] 已移除收藏: ${id}`)
    this.updateUI()
  }

  /**
   * 更新 UI
   */
  updateUI(): void {
    super.updateUI()

    this.updateFavoritesItem()
  }

  /**
   * 更新收藏项
   */
  updateFavoritesItem(): void {
    if (this.favorites.length === 0) {
      this.getElement('favoritesContent')?.html(this.renderNoFavorites())
    }
    else {
      this.getElement('favoritesContent')?.html(this.renderItem())
      this.bindEvents() // 确保事件绑定在更新后
    }
  }

  /**
   * 检查是否已收藏
   * @param id 样式属性ID
   * @returns 是否已收藏
   */
  isFavorite(id: string): boolean {
    return this.favorites.some(fav => fav.id === id)
  }

  /**
   * 获取收藏项图标
   * @param id 样式属性ID
   * @returns 图标字符串
   */
  getFavoriteIcon(id: string): string {
    return this.isFavorite(id) ? SYMBOLS.SHAPES.STAR_FILLED : SYMBOLS.SHAPES.STAR_EMPTY
  }

  /**
   * 切换收藏状态
   * @param item 样式属性项
   */
  toggleFavorite(item: StylePropertyItem): void {
    if (this.isFavorite(item.id)) {
      this.removeFavorite(item.id)
    }
    else {
      this.addFavorite(item)
    }
  }

  bindEvents(): void {
    // 绑定移除收藏事件
    this.getElement('favoriteItem')?.find('.remove').on('click', (e) => {
      e.stopPropagation()

      const $item = $(e.currentTarget).closest('.favorite-item')
      const id = $item.data('id')

      this.removeFavorite(id)

      // 触发移除回调
      this.props?.onRemove?.(id)
    })

    // 绑定点击收藏项事件
    this.getElement('favoriteItem')?.on('click', (e) => {
      const $item = $(e.currentTarget)
      const id = $item.data('id')
      const item = this.favorites.find(fav => fav.id === id)
      if (item) {
        // 触发选择回调
        this.props?.onSelect?.(id)
      }
    })
  }

  destroy(): void {
    super.destroy()
  }

  /**
   * 组件样式
   */
  styles(): string {
    return styles(this.className)
  }
}
